#include "esp_lyn_wifi.h"
#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_log.h"
#include "esp_wifi.h"
#include "esp_event.h"
#include "nvs_flash.h"
#include "esp_netif.h"
#include <string.h>
#define TAG "wifi_station"
#define SSID ""
#define PASSWORD ""

static lyn_wifi_listener_t lyn_wifi_listener = NULL;

// Wi-Fi 连接事件回调函数
void event_handler(void *arg, esp_event_base_t event_base,
                   int32_t event_id, void *event_data)
{
    if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_START)
    {
        ESP_LOGI(TAG, "WIFI启动成功");
        esp_wifi_connect();
        lyn_wifi_listener(WIFI_STATE_INIT, (char *)"");
    }
    else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED)
    {
        esp_wifi_connect();
        lyn_wifi_listener(WIFI_STATE_DISCONNECTED, (char *)"");
    }
    else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP)
    {
        ip_event_got_ip_t *event = (ip_event_got_ip_t *)event_data;
        ESP_LOGI(TAG, "连接成功ip地址: " IPSTR, IP2STR(&event->ip_info.ip));
        char ip_str[16];
        snprintf(ip_str, sizeof(ip_str), IPSTR, IP2STR(&event->ip_info.ip));
        lyn_wifi_listener(WIFI_STATE_CONNECTED, &ip_str);
    }
}

void lyn_wifi_init(const char *ssid, const char *password, lyn_wifi_listener_t listener)
{
    lyn_wifi_listener = listener;
    ESP_ERROR_CHECK(nvs_flash_init());
    esp_netif_init();
    ESP_ERROR_CHECK(esp_event_loop_create_default());
    esp_netif_create_default_wifi_sta();

    wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
    ESP_ERROR_CHECK(esp_wifi_init(&cfg));

    esp_event_handler_instance_t instance_any_id;
    esp_event_handler_instance_t instance_got_ip;
    ESP_ERROR_CHECK(esp_event_handler_instance_register(WIFI_EVENT,
                                                        ESP_EVENT_ANY_ID,
                                                        &event_handler,
                                                        NULL,
                                                        &instance_any_id));
    ESP_ERROR_CHECK(esp_event_handler_instance_register(IP_EVENT,
                                                        IP_EVENT_STA_GOT_IP,
                                                        &event_handler,
                                                        NULL,
                                                        &instance_got_ip));

    wifi_sta_config_t sta_ = {

    };
    for (int i = 0; i < strlen(ssid); i++)
    {
        sta_.ssid[i] = ssid[i];
    }
    for (int i = 0; i < strlen(password); i++)
    {
        sta_.password[i] = password[i];
    }
    ESP_LOGI(TAG,"WIFI名称 %s",(char*)sta_.ssid);
    wifi_config_t wifi_config = {
        .sta = sta_,
    };
    ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));
    ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_STA, &wifi_config));
    ESP_ERROR_CHECK(esp_wifi_start());
}
